class Compiler {
  constructor (vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  // 编译模板池里文本和元素节点
  compile (el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }
      // 判断是否有子节点 递归
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }

    })
  }
  compileElement (node) {
    Array.from(node.attributes).forEach(attr => {
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        // v-text => text
        attrName = attrName.substr(2)
        let key = attr.value
        this.update(node, key, attrName)
      }
    })
  }
  update (node, key, attrName) {
    let updateFn
    let attrNameArr = attrName.split(":")
    if (attrNameArr.length > 1) {
      let fn = (this.vm && this.vm.$options && this.vm.$options.methods) 
      ? this.vm.$options.methods[key] : () =>{}
      updateFn = this[attrNameArr[0] + 'Update']
      updateFn && updateFn.call(this, node, fn, attrNameArr[1])
    } else {
      updateFn = this[attrName + 'Update']
      updateFn && updateFn.call(this, node, this.vm[key], key)
    }
   
  }
  // 处理v-on
  onUpdate (node, fn, event) {
    node.addEventListener(event, fn)
  }
  // 处理v-html
  htmlUpdate (node, value, key) {
    // console.log(node, value, key)
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }
  // 处理v-text
  textUpdate (node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  // v-module
  moduleUpdate (node, value,key) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }
  // 处理文本节点
  compileText (node) {
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    // debugger
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent= value.replace(reg,this.vm[key])
      // 创建watcher
      new Watcher(this.vm, key, (newValue) => {
        node.textContent= value.replace(reg,newValue)
      })
    }
  }
  // 判断元素属性是否是指令
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }
  // 判断是否是文本节点
  isTextNode (node) {
    return node.nodeType === 3
  }
  // 判断是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
}